<template>
<div class="card" style="text-align: center;padding: 40px 20px;width: 50%;">
  <el-form ref="formRef" :rules="data.rules" :model="data.form" >
    <el-form-item :label-width="120" prop="password" label="原密码：">
      <el-input size="lager" v-model="data.form.password" placeholder="请输入原密码" show-password></el-input>
    </el-form-item>
    <el-form-item :label-width="120" prop="newPassword" label="新密码：">
      <el-input size="lager" v-model="data.form.newPassword" placeholder="请输入新密码"  show-password></el-input>
    </el-form-item>
    <el-form-item :label-width="120" prop="ConfirmPassword" label="确认密码：" required>
      <el-input size="lager" v-model="data.form.ConfirmPassword" placeholder="请确认密码"  show-password></el-input>
    </el-form-item>
  </el-form>
  <div>
    <el-button type="primary" @click="savePassword">保存密码</el-button>
  </div>
</div>
</template>

<script setup>
import {reactive,ref} from "vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认密码'))
  }else {
    if (value !== data.form.newPassword) {
      callback('两次密码不一致')
    }
    else{
      callback()
    }
  }
}

const formRef = ref();
const data = reactive({
  user:JSON.parse(localStorage.getItem('xm-pro-user')),
  form:{},
  rules:{
    password:[
      {required:true,message:'请输入原密码',trigger:'blur'}
    ],
    newPassword:[
      {required:true,message:'请输入新密码',trigger:'blur'}
    ],
    ConfirmPassword:[
      {validator:validatePass,trigger:'blur'}
    ]


  }
})

const savePassword = ()=>{
  data.form.id=data.user.id;
  data.form.role = data.user.role;
  console.log(data.form.newPassword);
  formRef.value.validate((valid)=>{
    if(valid){
      request.post('updatePassword',data.form).then(res=>{
        if(res.code === '200'){
          ElMessage.success("修改成功");
        }else{
          ElMessage.error(res.msg);
        }

      })

    }
  })
}


</script>
